import React, { useState, useEffect } from 'react'
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic,
  Alert,
  Badge,
  Rate,
  Tree,
  Tabs,
  Upload,
  Image,
  Divider,
  Empty,
  Progress,
  Switch
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  DownloadOutlined,
  UploadOutlined,
  CopyOutlined,
  ExportOutlined,
  ImportOutlined,
  StarOutlined,
  EyeOutlined,
  FireOutlined,
  HeartOutlined,
  PlayCircleOutlined,
  SendOutlined,
  FolderOpenOutlined,
  SettingOutlined,
  DashboardOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { ThemeScenario, ThemeScenarioTemplate, ThemeScenarioQuery, ThemeScenarioStats, PageResult } from '@/types/index'

const { Search } = Input
const { TextArea } = Input
const { TabPane } = Tabs

interface ThemeScenarioManagementProps {}

const ThemeScenarioManagement: React.FC<ThemeScenarioManagementProps> = () => {
  // 状态管理
  const [loading, setLoading] = useState(false)
  const [tableLoading, setTableLoading] = useState(false)
  const [scenarios, setScenarios] = useState<ThemeScenario[]>([])
  const [templates, setTemplates] = useState<ThemeScenarioTemplate[]>([])
  const [stats, setStats] = useState<ThemeScenarioStats>()
  const [recommendedScenarios, setRecommendedScenarios] = useState<ThemeScenario[]>([])
  const [popularScenarios, setPopularScenarios] = useState<ThemeScenario[]>([])
  
  // 分页和查询
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`
  })
  
  const [query, setQuery] = useState<ThemeScenarioQuery>({
    current: 1,
    size: 10
  })
  
  // 弹窗状态
  const [createModalVisible, setCreateModalVisible] = useState(false)
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [templateModalVisible, setTemplateModalVisible] = useState(false)
  const [copyModalVisible, setCopyModalVisible] = useState(false)
  const [rateModalVisible, setRateModalVisible] = useState(false)
  const [previewModalVisible, setPreviewModalVisible] = useState(false)
  
  // 选中状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [selectedScenario, setSelectedScenario] = useState<ThemeScenario>()
  const [activeTab, setActiveTab] = useState('all')
  
  // 表单实例
  const [createForm] = Form.useForm()
  const [editForm] = Form.useForm()
  const [templateForm] = Form.useForm()
  const [copyForm] = Form.useForm()
  const [rateForm] = Form.useForm()

  // 场景类型选项
  const scenarioTypeOptions = [
    { label: '仪表盘', value: 'DASHBOARD' },
    { label: '报表', value: 'REPORT' },
    { label: '分析', value: 'ANALYSIS' },
    { label: '监控', value: 'MONITOR' },
    { label: '展示', value: 'PRESENTATION' },
    { label: '交互式', value: 'INTERACTIVE' },
    { label: '实时', value: 'REALTIME' },
    { label: '自定义', value: 'CUSTOM' }
  ]

  // 应用类型选项
  const applicationTypeOptions = [
    { label: 'PC端', value: 'PC' },
    { label: '移动端', value: 'MOBILE' },
    { label: '平板端', value: 'PAD' },
    { label: '大屏端', value: 'LARGE_SCREEN' },
    { label: '电视端', value: 'TV' },
    { label: '通用', value: 'UNIVERSAL' }
  ]

  // 状态选项
  const statusOptions = [
    { label: '草稿', value: 'DRAFT' },
    { label: '已提交', value: 'SUBMITTED' },
    { label: '已审批', value: 'APPROVED' },
    { label: '已拒绝', value: 'REJECTED' },
    { label: '已发布', value: 'PUBLISHED' },
    { label: '已归档', value: 'ARCHIVED' }
  ]

  // 获取主题场景列表
  const fetchScenarios = async (params: ThemeScenarioQuery = query) => {
    setTableLoading(true)
    try {
      const response = await fetch('/api/theme-scenario/page', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(params)
      })
      
      if (response.ok) {
        const result: PageResult<ThemeScenario> = await response.json()
        setScenarios(result.records)
        setPagination(prev => ({
          ...prev,
          current: result.current,
          total: result.total
        }))
      } else {
        message.error('获取主题场景列表失败')
      }
    } catch (error) {
      console.error('获取主题场景列表失败:', error)
      message.error('网络错误，请重试')
    } finally {
      setTableLoading(false)
    }
  }

  // 获取模板列表
  const fetchTemplates = async () => {
    try {
      const response = await fetch('/api/theme-scenario-template/recommended?limit=10')
      if (response.ok) {
        const result = await response.json()
        setTemplates(result)
      }
    } catch (error) {
      console.error('获取模板列表失败:', error)
    }
  }

  // 获取统计信息
  const fetchStats = async () => {
    try {
      const response = await fetch('/api/theme-scenario/statistics')
      if (response.ok) {
        const result = await response.json()
        setStats(result)
      }
    } catch (error) {
      console.error('获取统计信息失败:', error)
    }
  }

  // 获取推荐场景
  const fetchRecommendedScenarios = async () => {
    try {
      const response = await fetch('/api/theme-scenario/recommended?limit=6')
      if (response.ok) {
        const result = await response.json()
        setRecommendedScenarios(result)
      }
    } catch (error) {
      console.error('获取推荐场景失败:', error)
    }
  }

  // 获取热门场景
  const fetchPopularScenarios = async () => {
    try {
      const response = await fetch('/api/theme-scenario/popular?limit=6')
      if (response.ok) {
        const result = await response.json()
        setPopularScenarios(result)
      }
    } catch (error) {
      console.error('获取热门场景失败:', error)
    }
  }

  // 刷新数据
  const refreshData = () => {
    fetchScenarios()
    fetchTemplates()
    fetchStats()
    fetchRecommendedScenarios()
    fetchPopularScenarios()
  }

  // 初始化
  useEffect(() => {
    refreshData()
  }, [])

  // 表格列定义
  const columns: ColumnsType<ThemeScenario> = [
    {
      title: '场景名称',
      dataIndex: 'displayName',
      key: 'displayName',
      width: 200,
      render: (text, record) => (
        <Space direction="vertical" size={0}>
          <span style={{ fontWeight: 500 }}>{text}</span>
          <span style={{ fontSize: '12px', color: '#666' }}>{record.name}</span>
        </Space>
      )
    },
    {
      title: '场景类型',
      dataIndex: 'scenarioType',
      key: 'scenarioType',
      width: 100,
      render: (type) => {
        const typeMap = {
          DASHBOARD: { color: 'blue', text: '仪表盘' },
          REPORT: { color: 'green', text: '报表' },
          ANALYSIS: { color: 'orange', text: '分析' },
          MONITOR: { color: 'red', text: '监控' },
          PRESENTATION: { color: 'purple', text: '展示' },
          INTERACTIVE: { color: 'cyan', text: '交互式' },
          REALTIME: { color: 'magenta', text: '实时' },
          CUSTOM: { color: 'default', text: '自定义' }
        }
        const config = typeMap[type as keyof typeof typeMap]
        return <Tag color={config?.color}>{config?.text}</Tag>
      }
    },
    {
      title: '应用场景',
      dataIndex: 'applicationType',
      key: 'applicationType',
      width: 100,
      render: (type) => {
        const typeMap = {
          PC: 'PC端',
          MOBILE: '移动端',
          PAD: '平板端',
          LARGE_SCREEN: '大屏端',
          TV: '电视端',
          UNIVERSAL: '通用'
        }
        return typeMap[type as keyof typeof typeMap] || type
      }
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      width: 120,
      render: (rating) => (
        <Space>
          <Rate disabled value={rating} allowHalf />
          <span>({rating?.toFixed(1) || '0.0'})</span>
        </Space>
      )
    },
    {
      title: '访问次数',
      dataIndex: 'accessCount',
      key: 'accessCount',
      width: 100,
      render: (count) => <Badge count={count} showZero overflowCount={999} />
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const statusMap = {
          DRAFT: { color: 'default', text: '草稿' },
          SUBMITTED: { color: 'processing', text: '已提交' },
          APPROVED: { color: 'success', text: '已审批' },
          REJECTED: { color: 'error', text: '已拒绝' },
          PUBLISHED: { color: 'success', text: '已发布' },
          ARCHIVED: { color: 'warning', text: '已归档' },
          DELETED: { color: 'error', text: '已删除' }
        }
        const config = statusMap[status as keyof typeof statusMap]
        return <Tag color={config?.color}>{config?.text}</Tag>
      }
    },
    {
      title: '标识',
      key: 'badges',
      width: 120,
      render: (_, record) => (
        <Space>
          {record.isRecommended && (
            <Tooltip title="推荐场景">
              <StarOutlined style={{ color: '#faad14' }} />
            </Tooltip>
          )}
          {record.isPublic && (
            <Tooltip title="公开场景">
              <EyeOutlined style={{ color: '#52c41a' }} />
            </Tooltip>
          )}
          {record.status === 'PUBLISHED' && (
            <Tooltip title="已发布">
              <Badge color="green" />
            </Tooltip>
          )}
        </Space>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      render: (time) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'actions',
      width: 250,
      fixed: 'right',
      render: (_, record) => (
        <Space wrap>
          <Tooltip title="预览">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => handlePreview(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="复制">
            <Button
              type="text"
              icon={<CopyOutlined />}
              onClick={() => handleShowCopyModal(record)}
            />
          </Tooltip>
          <Tooltip title="评分">
            <Button
              type="text"
              icon={<HeartOutlined />}
              onClick={() => handleShowRateModal(record)}
            />
          </Tooltip>
          {record.status === 'DRAFT' && (
            <Tooltip title="发布">
              <Button
                type="text"
                icon={<SendOutlined />}
                onClick={() => handlePublish(record)}
              />
            </Tooltip>
          )}
          {record.status === 'PUBLISHED' && (
            <Tooltip title="归档">
              <Button
                type="text"
                icon={<FolderOpenOutlined />}
                onClick={() => handleArchive(record)}
              />
            </Tooltip>
          )}
          <Popconfirm
            title="确定要删除此场景吗？"
            onConfirm={() => handleDelete(record)}
          >
            <Tooltip title="删除">
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ]

  // 事件处理函数
  const handleSearch = (keyword: string) => {
    const newQuery = { ...query, keyword, current: 1 }
    setQuery(newQuery)
    fetchScenarios(newQuery)
  }

  const handleTabChange = (key: string) => {
    setActiveTab(key)
    let newQuery = { ...query, current: 1 }
    
    switch (key) {
      case 'recommended':
        newQuery.isRecommended = true
        break
      case 'published':
        newQuery.status = 'PUBLISHED'
        break
      case 'draft':
        newQuery.status = 'DRAFT'
        break
      case 'my':
        newQuery.creator = 'current_user'
        break
      default:
        delete newQuery.isRecommended
        delete newQuery.status
        delete newQuery.creator
    }
    
    setQuery(newQuery)
    fetchScenarios(newQuery)
  }

  const handleTableChange = (page: any) => {
    const newQuery = {
      ...query,
      current: page.current,
      size: page.pageSize
    }
    setQuery(newQuery)
    fetchScenarios(newQuery)
  }

  const handleCreate = () => {
    setCreateModalVisible(true)
  }

  const handleCreateSubmit = async () => {
    try {
      const values = await createForm.validateFields()
      const response = await fetch('/api/theme-scenario', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...values,
          components: []
        })
      })
      
      if (response.ok) {
        message.success('创建成功')
        setCreateModalVisible(false)
        createForm.resetFields()
        fetchScenarios()
      } else {
        message.error('创建失败')
      }
    } catch (error) {
      console.error('创建失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handleEdit = (record: ThemeScenario) => {
    setSelectedScenario(record)
    editForm.setFieldsValue(record)
    setEditModalVisible(true)
  }

  const handleEditSubmit = async () => {
    try {
      const values = await editForm.validateFields()
      const response = await fetch(`/api/theme-scenario/${selectedScenario?.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...values,
          components: []
        })
      })
      
      if (response.ok) {
        message.success('更新成功')
        setEditModalVisible(false)
        fetchScenarios()
      } else {
        message.error('更新失败')
      }
    } catch (error) {
      console.error('更新失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handleShowCopyModal = (record: ThemeScenario) => {
    setSelectedScenario(record)
    copyForm.setFieldsValue({ newName: record.displayName + '_副本' })
    setCopyModalVisible(true)
  }

  const handleCopy = async () => {
    try {
      const values = await copyForm.validateFields()
      const response = await fetch(`/api/theme-scenario/${selectedScenario?.id}/copy?newName=${values.newName}`, {
        method: 'POST'
      })
      
      if (response.ok) {
        message.success('复制成功')
        setCopyModalVisible(false)
        copyForm.resetFields()
        fetchScenarios()
      } else {
        message.error('复制失败')
      }
    } catch (error) {
      console.error('复制失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handleShowRateModal = (record: ThemeScenario) => {
    setSelectedScenario(record)
    rateForm.setFieldsValue({ rating: record.rating })
    setRateModalVisible(true)
  }

  const handleRate = async () => {
    try {
      const values = await rateForm.validateFields()
      const response = await fetch(`/api/theme-scenario/${selectedScenario?.id}/rate`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ rating: values.rating })
      })
      
      if (response.ok) {
        message.success('评分成功')
        setRateModalVisible(false)
        fetchScenarios()
      } else {
        message.error('评分失败')
      }
    } catch (error) {
      console.error('评分失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handlePreview = (record: ThemeScenario) => {
    setSelectedScenario(record)
    setPreviewModalVisible(true)
    // 增加访问次数
    fetch(`/api/theme-scenario/${record.id}/access`, { method: 'POST' })
  }

  const handlePublish = async (record: ThemeScenario) => {
    try {
      const response = await fetch(`/api/theme-scenario/${record.id}/publish`, {
        method: 'POST'
      })
      
      if (response.ok) {
        message.success('发布成功')
        fetchScenarios()
      } else {
        message.error('发布失败')
      }
    } catch (error) {
      console.error('发布失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handleArchive = async (record: ThemeScenario) => {
    try {
      const response = await fetch(`/api/theme-scenario/${record.id}/archive`, {
        method: 'POST'
      })
      
      if (response.ok) {
        message.success('归档成功')
        fetchScenarios()
      } else {
        message.error('归档失败')
      }
    } catch (error) {
      console.error('归档失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handleDelete = async (record: ThemeScenario) => {
    try {
      const response = await fetch(`/api/theme-scenario/${record.id}`, {
        method: 'DELETE'
      })
      
      if (response.ok) {
        message.success('删除成功')
        fetchScenarios()
      } else {
        message.error('删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      message.error('网络错误，请重试')
    }
  }

  const handleFromTemplate = () => {
    setTemplateModalVisible(true)
  }

  const handleTemplateSubmit = async () => {
    try {
      const values = await templateForm.validateFields()
      const response = await fetch('/api/theme-scenario/create-from-template', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(values)
      })
      
      if (response.ok) {
        message.success('从模板创建成功')
        setTemplateModalVisible(false)
        templateForm.resetFields()
        fetchScenarios()
      } else {
        message.error('从模板创建失败')
      }
    } catch (error) {
      console.error('从模板创建失败:', error)
      message.error('网络错误，请重试')
    }
  }

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(selectedRowKeys)
    }
  }

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计信息 */}
      {stats && (
        <Row gutter={16} style={{ marginBottom: '24px' }}>
          <Col span={5}>
            <Card>
              <Statistic
                title="场景总数"
                value={stats.totalScenarios}
                prefix={<DashboardOutlined />}
              />
            </Card>
          </Col>
          <Col span={5}>
            <Card>
              <Statistic
                title="已发布"
                value={stats.publishedScenarios}
                prefix={<SendOutlined />}
              />
            </Card>
          </Col>
          <Col span={5}>
            <Card>
              <Statistic
                title="草稿"
                value={stats.draftScenarios}
                prefix={<EditOutlined />}
              />
            </Card>
          </Col>
          <Col span={5}>
            <Card>
              <Statistic
                title="总访问量"
                value={stats.totalAccess}
                prefix={<EyeOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="平均评分"
                value={stats.averageRating}
                precision={1}
                prefix={<StarOutlined />}
              />
            </Card>
          </Col>
        </Row>
      )}

      {/* 推荐场景 */}
      {recommendedScenarios.length > 0 && (
        <Card 
          title="推荐场景" 
          style={{ marginBottom: '24px' }}
          extra={
            <Button 
              type="link" 
              onClick={() => handleTabChange('recommended')}
            >
              查看更多
            </Button>
          }
        >
          <Row gutter={16}>
            {recommendedScenarios.map(scenario => (
              <Col span={4} key={scenario.id}>
                <Card
                  size="small"
                  hoverable
                  cover={
                    scenario.thumbnailUrl ? (
                      <Image
                        src={scenario.thumbnailUrl}
                        height={120}
                        style={{ objectFit: 'cover' }}
                        preview={false}
                      />
                    ) : (
                      <div 
                        style={{
                          height: 120,
                          background: '#f5f5f5',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center'
                        }}
                      >
                        <DashboardOutlined style={{ fontSize: '24px', color: '#ccc' }} />
                      </div>
                    )
                  }
                  actions={[
                    <Tooltip title="预览场景">
                      <EyeOutlined onClick={() => handlePreview(scenario)} />
                    </Tooltip>,
                    <Tooltip title="复制场景">
                      <CopyOutlined onClick={() => handleShowCopyModal(scenario)} />
                    </Tooltip>
                  ]}
                >
                  <Card.Meta
                    title={scenario.displayName}
                    description={
                      <div>
                        <div style={{ marginBottom: '4px' }}>
                          <Rate disabled value={scenario.rating} allowHalf />
                        </div>
                        <div style={{ fontSize: '12px', color: '#666' }}>
                          访问 {scenario.accessCount} 次
                        </div>
                      </div>
                    }
                  />
                </Card>
              </Col>
            ))}
          </Row>
        </Card>
      )}

      {/* 主要内容区域 */}
      <Card>
        {/* 顶部操作栏 */}
        <div style={{ marginBottom: '16px' }}>
          <Row justify="space-between" align="middle">
            <Col>
              <Space>
                <Search
                  placeholder="搜索场景名称、描述"
                  allowClear
                  style={{ width: 300 }}
                  onSearch={handleSearch}
                />
              </Space>
            </Col>
            <Col>
              <Space>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={handleCreate}
                >
                  新建场景
                </Button>
                <Button
                  icon={<SettingOutlined />}
                  onClick={handleFromTemplate}
                >
                  从模板创建
                </Button>
                <Button
                  icon={<ImportOutlined />}
                >
                  导入场景
                </Button>
                <Button
                  icon={<ExportOutlined />}
                  disabled={selectedRowKeys.length === 0}
                >
                  导出场景
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={refreshData}
                >
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        {/* 类型筛选标签 */}
        <Tabs activeKey={activeTab} onChange={handleTabChange}>
          <TabPane tab="全部场景" key="all" />
          <TabPane tab="推荐场景" key="recommended" />
          <TabPane tab="已发布" key="published" />
          <TabPane tab="草稿" key="draft" />
          <TabPane tab="我的场景" key="my" />
        </Tabs>

        {/* 场景列表表格 */}
        <Table
          rowKey="id"
          columns={columns}
          dataSource={scenarios}
          loading={tableLoading}
          pagination={{
            ...pagination,
            onChange: (page, pageSize) => handleTableChange({ current: page, pageSize })
          }}
          rowSelection={rowSelection}
          scroll={{ x: 1600 }}
          size="middle"
        />
      </Card>
    </div>
  )
}

export default ThemeScenarioManagement